package com.company.chatRoom;

import com.company.utils.JSonUtil;
import com.company.utils.MyException;
import org.json.simple.JSONObject;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @Auther Xue
 * @Date 2021/4/28
 * @Version 1.0
 * @Desc    服务器发送线程
 */
public class ServerSend implements Runnable {
    private String username;
    private static ObjectOutputStream oos;

    public ServerSend(String name) {
        this.username = name;
    }

    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String str = scanner.nextLine();
//            JSONObject obj = new JSONObject();
            HashMap<String, String> obj = new HashMap<>();
            obj.put("type", "chat");
            obj.put("user", username);
            obj.put("msg", str);
            System.out.println(obj);
            dispatch(obj);
        }
        }
    public static void dispatch(HashMap<String, String> obj) {
        for (Socket socket : ChatServer.getSockets()) {
            try {
                if (Utils.isServerClose(socket)) {
                    socket.close();
                    System.out.println("断开连接");
                    break;
                }
                oos = Utils.getOOSBySocket(socket);
                JSONObject rst = new JSONObject();
                rst.put("type", obj.get("type"));
                rst.put("user", obj.get("user"));
                rst.put("msg", obj.get("msg"));
                oos.writeObject(JSonUtil.obj2String(rst));
                oos.flush();
            } catch (IOException e) {
                MyException.logExceptionMessage(e);
                try {
                    socket.close();
                    System.out.println("ServerWriter断开连接");
                    ChatServer.closeAllThread();
                    break;
                } catch (IOException ex) {
                    MyException.logExceptionMessage(e);
                }
            }
        }
    }


    public String getUserName() {
        return username;
    }

    public void setUserName(String name) {
        this.username = name;
    }

}
